package com.lemote.service.order.impl;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.lemote.core.Page;
import com.lemote.core.PropertyFilter;
import com.lemote.dao.order.CircuitBoardDao;
import com.lemote.entity.CircuitBoard;
import com.lemote.entity.FailReoprt;
import com.lemote.entity.FlowTask;
import com.lemote.entity.User;
import com.lemote.service.impl.BaseServiceImpl;
import com.lemote.service.order.CircuitBoardService;
import com.lemote.service.order.FlowTaskService;
import com.lemote.service.order.OrderService;
import com.lemote.utils.DataUtils;

/**
 * 
 * @author wuhui
 * @time 2011-7-19 下午09:00:29
 * @Version:0.0.1
 * @since smt
 */
@Component
public class CircuitBoardServiceImpl extends
		BaseServiceImpl<CircuitBoard, Long, CircuitBoardDao> implements
		CircuitBoardService {

	private FlowTaskService flowTaskService;

	private OrderService orderService;

	@Autowired
	public void setFlowTaskService(FlowTaskService flowTaskService) {
		this.flowTaskService = flowTaskService;
	}

	@Autowired
	@Override
	public void setEntityDao(CircuitBoardDao circuitBoardDao) {
		entityDao = circuitBoardDao;
	}

	@Override
	public Page<CircuitBoard> searchBoard(Page<CircuitBoard> page,
			List<PropertyFilter> filters,FlowTask flowTask) {
		return entityDao.searchBoard(page, filters, flowTask);
	}

	@Override
	public Boolean autoTest(List<CircuitBoard> boards,User user) {
		if (boards == null) {
			return false;
		}
		String botpath = DataUtils.getPropertiesValue("bot.aoi.path");
		FlowTask topTask = flowTaskService.getTaskByTaskName("top_aoi_test");
		FlowTask repairTask = flowTaskService.getTaskByTaskName("repair");
		try {
		if (botpath != null && !"".equals(StringUtils.trim(botpath))) {
			List<File> files = DataUtils.fileList(new File(botpath), ".txt");
			if (files != null) {
				for (CircuitBoard board : boards) {
					boolean taskflag = false;
					List<String> details = new ArrayList<String>();
					for (File file : files) {
						String fileName = file.getName();
						if (fileName.startsWith(board.getIcNo())) {
							Map<String,List<String>> contents = readFile(file);
							List<String> mains = contents.get("Main");
							if (mains!=null&&mains.size()>0) {
								String content = mains.get(0);
								if (StringUtils.contains(content, "\"BOTTOM\"")) {
									if (boardTest(content)) {
										continue;
									}else {
										taskflag = true;
									}
									details.addAll(contents.get("Detail"));
								}
							}
						}
					}
					board.setPreTask(board.getFlowTask());
					if (taskflag) {
						List<FailReoprt> fails = new ArrayList<FailReoprt>();
						for (String st : details) {
							if (!"".equals(StringUtils.trim(st))) {
								Map<String,String> detail = getDetails(st);
								FailReoprt fail = new FailReoprt();
								fail.setBoard(board);
								fail.setRecorder(user);
								fail.setJobName(topTask.getTaskName());
								fail.setErrorCode(detail.get("FalseDefectCode"));
								fail.setLocation(detail.get("Location"));
								fails.add(fail);
							}
						}
						board.setFails(fails);
						board.setStatus("1");
						board.setFlowTask(repairTask);
					}else {
						board.setFlowTask(topTask);	
					}
					update(board);
				}
			}
		}
		} catch (IOException e) {
			e.printStackTrace();
			
		}
		return true;
	}
	
	@Override
	public Boolean autoTopTest(List<CircuitBoard> boards,User user) {
		if (boards == null) {
			return false;
		}
		String botpath = DataUtils.getPropertiesValue("top.aoi.path");
		FlowTask macTask = flowTaskService.getTaskByTaskName("mac_input");
		FlowTask repairTask = flowTaskService.getTaskByTaskName("repair");
		try {
		if (botpath != null && !"".equals(StringUtils.trim(botpath))) {
			List<File> files = DataUtils.fileList(new File(botpath), ".txt");
			if (files != null) {
				for (CircuitBoard board : boards) {
					boolean taskflag = false;
					List<String> details = new ArrayList<String>();
					for (File file : files) {
						String fileName = file.getName();
						if (fileName.startsWith(board.getIcNo())) {
							Map<String,List<String>> contents = readFile(file);
							List<String> mains = contents.get("Main");
							if (mains!=null&&mains.size()>0) {
								String content = mains.get(0);
								if (StringUtils.contains(content, "\"TOP\"")) {
									if (boardTest(content)) {
										continue;
									}else {
										taskflag = true;
									}
									details.addAll(contents.get("Detail"));
								}
							}
						}
					}
					board.setPreTask(board.getFlowTask());
					if (taskflag) {
						List<FailReoprt> fails = new ArrayList<FailReoprt>();
						for (String st : details) {
							if (!"".equals(StringUtils.trim(st))) {
								Map<String,String> detail = getDetails(st);
								FailReoprt fail = new FailReoprt();
								fail.setBoard(board);
								fail.setRecorder(user);
								fail.setJobName(macTask.getTaskName());
								fail.setErrorCode(detail.get("FalseDefectCode"));
								fail.setLocation(detail.get("Location"));
								fails.add(fail);
							}
						}
						board.setFails(fails);
						board.setFlowTask(repairTask);
						board.setStatus("1");
					}else {
						board.setFlowTask(macTask);	
					}
					update(board);
				}
			}
		}
		} catch (IOException e) {
			e.printStackTrace();
			
		}
		return true;
	}
	
	
	public Map<String,String> getDetails(String content){
		Map<String,String> map = new HashMap<String, String>();
		if (content!=null&&content.length()>0) {
			content = content.substring(1, content.length()-1);
			String[] arr = content.split("\",\"");
			if (arr!=null&&arr.length>=3) {
				map.put("Location", arr[0]);
				map.put("FalseDefectCode", arr[2]);
			}
		}
		return map;
	}
	
	/**
	  * 读取文件 
	  * @param file
	  * @return
	  * @throws IOException
	 */
	public Map<String,List<String>> readFile(File file) throws IOException{
		Map<String,List<String>> map = new HashMap<String, List<String>>();
		List<String> lines = FileUtils.readLines(file);
		if (lines!=null&&lines.size()>5) {
			List<String> mains = new ArrayList<String>();
			List<String> details = new ArrayList<String>();
			for (int i=0;i<lines.size();i++) {
				if ("[Main]".equals(StringUtils.trim(lines.get(i)))) {
					i+=2;
					mains.add(lines.get(i));
				}
				if ("[Detail]".equals(StringUtils.trim(lines.get(i)))) {
					i+=2;
					details.addAll(lines.subList(i, lines.size()));
					break;
				}
			}
			map.put("Main", mains);
			map.put("Detail", details);
		}
		return map;
	}
	
	public boolean boardTest(String content){
		
		return StringUtils.contains(content, "\"OK\"");
	}

	@Override
	public List<CircuitBoard> getAllBoard(List<Long> roles) {
		List<FlowTask> tasks = flowTaskService.getAll();
		List<FlowTask> nowTasks = new ArrayList<FlowTask>();
		if (roles == null || tasks == null) {
			return null;
		}
		for (FlowTask flowTask : tasks) {
			if (roles.contains(flowTask.getRole().getId())) {
				nowTasks.add(flowTask);
			}
		}
		return entityDao.getAllBoard(nowTasks);
	}

}
